package com.exam.web.action.privilege;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.exam.utils.MD5;
import com.exam.utils.ValidateFile;
import com.exam.bean.PageView;
import com.exam.bean.QueryResult;
import com.exam.bean.Sex;
import com.exam.bean.UseRole;
import com.exam.bean.privilege.Department;
import com.exam.bean.privilege.Employee;
import com.exam.bean.privilege.IDCard;
import com.exam.bean.privilege.PrivilegeGroup;
import com.exam.service.privilege.DepartmentService;
import com.exam.service.privilege.EmployeeService;
import com.exam.service.privilege.PrivilegeGroupService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller("employeeAction")
@Scope("prototype")
public class EmployeeAction extends ActionSupport {
	
	private static final long serialVersionUID = -5605445941610677727L;

	@Resource
	private EmployeeService employeeService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private PrivilegeGroupService privilegeGroupService;
	
	private int page;//分页
	private String query;//查询
	private PageView<Employee> pageView;//记录集
	private Employee employee;//用户
	private String sex;//性别
	private String usercate;//用户类别
	private String username;//用户名
	private String cardno;//身份证号
	private List<Department> departments;//所属组织结构
	private List<PrivilegeGroup> privilegegroups;//所拥有的角色
	private Integer[] departmentids;
	private Integer[] privilegegroupids;
	private String[] employeeids;
	
	
	private File imagefile;
	private String imagefileContentType;
	private String imagefileFileName;
	
	/**
	 * 用户登录
	 * @return
	 * @throws Exception
	 */
	public String login()throws Exception{
		return "success";
	}
	
	
	/**
	 * 判断用户名是否存在
	 * @return
	 * @throws Exception
	 */
	public String check()throws Exception{
		
		String message="";
		if(this.getUsername()!=null&&!"".equals(this.getUsername())){
			if(!employeeService.exist(this.getUsername())){
				message="<font color=\"green\">登录账号可用</font>";
				//System.out.println(this.getUsername());
			}
			else{
				message="<font color=\"red\">登录账号已存在</font>";
				//System.out.println(message);
			}
		}
		ActionContext.getContext().put("check", message);
		return "check";
	}
	
	/**
	 * 判断身份证号否存在
	 * @return
	 * @throws Exception
	 */
	public String checkCardno()throws Exception{
		
		String message="";
		if(this.getCardno()!=null&&!"".equals(this.getCardno())){
			if(employeeService.existCardno(this.getCardno())){
				message="<font color=\"red\">身份证号已存在</font>";
			}
		}
		ActionContext.getContext().put("check", message);
		return "check";
	}
	
	/**
	 * 用户显示
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="view")
	public String list()throws Exception{
		
		PageView<Employee> pageView=new PageView<Employee>(12,this.getPage());
		int firstIndex=(this.getPage()-1)*pageView.getMaxResult();
		
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("username", "desc");
		
		if("true".equals(this.getQuery())){
			if(this.getEmployee().getRealname()!=null && !"".equals(this.getEmployee().getRealname().trim())){
				StringBuffer jpql=new StringBuffer("");
				List<Object> params=new ArrayList<Object>();
				
				jpql.append("o.username like ?"+ (params.size()+1));
				params.add("%"+ this.getEmployee().getRealname().trim()+ "%");
				jpql.append(" or o.realname like ?"+ (params.size()+1));
				params.add("%"+ this.getEmployee().getRealname().trim()+ "%");
				jpql.append(" or o.phone like ?"+ (params.size()+1));
				params.add("%"+ this.getEmployee().getRealname().trim()+ "%");
				jpql.append(" or o.email like ?"+ (params.size()+1));
				params.add("%"+ this.getEmployee().getRealname().trim()+ "%");
				jpql.append(" or o.idcard.cardno like ?"+ (params.size()+1));
				params.add("%"+ this.getEmployee().getRealname().trim()+ "%");
				/*jpql.append(" or o.departments.name like ?"+ (params.size()+1));
				params.add("%"+ this.getEmployee().getRealname().trim()+ "%");//*/
				
				QueryResult<Employee> qr=employeeService.getScrollData(Employee.class
						,firstIndex,pageView.getMaxResult(),jpql.toString(),params.toArray(),orderby);
				
				pageView.setQueryResult(qr);
				this.setPageView(pageView);
				return SUCCESS;
			}
		}
		
		QueryResult<Employee> qr=employeeService.getScrollData(Employee.class
				,firstIndex,pageView.getMaxResult(),orderby);
		pageView.setQueryResult(qr);
		this.setPageView(pageView);
		return SUCCESS;
	}

	
	/**
	 * 添加用户
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="insert")
	public String add()throws Exception{
		
		Employee employee = this.getEmployee();
		employee.setUsername(this.getUsername());
		employee.setPassword(MD5.MD5Encode(employee.getPassword()));
		employee.setSex(Sex.valueOf(this.getSex()));
		employee.setUsercate(UseRole.valueOf(this.getUsercate()));
		if(this.getDepartmentids()!=null && this.getDepartmentids().length>0){
			for(Integer id : this.getDepartmentids()){
				employee.addDepartment(new Department(id));
			}
		}
		if(this.getPrivilegegroupids()!=null && this.getPrivilegegroupids().length>0){
			for(Integer id : this.getPrivilegegroupids()){
				employee.addPrivilegegroup(new PrivilegeGroup(id));
			}
		}
		if(this.getImagefile()!=null&&this.getImagefile().length()>0){
			if(!ValidateFile.validateImageFileType(this.getImagefile(),this.getImagefileContentType()
					,this.getImagefileFileName())){
				ActionContext.getContext().put("message", "文件格式不正确,只允许上传gif/jpg/png/bmp图片！");
				ActionContext.getContext().put("urladdress", "javascript:history.back()");
				return "message";
			}
			if(this.getImagefile().length()>204800){
				ActionContext.getContext().put("message", "图片不能大于200K！");
				ActionContext.getContext().put("urladdress", "javascript:history.back()");
				return "message";
			}
			String logopath="/images/employee/"+this.getUsername();
			
			String ext = ValidateFile.getExtension(this.getImagefileFileName());
			String filename = UUID.randomUUID().toString()+ "."+ext;//构建文件名称
			
			String realpath = ServletActionContext.getServletContext().getRealPath(logopath);
			File file = new File(realpath);
			if(!file.exists()) file.mkdirs();
			FileUtils.copyFile(this.getImagefile(), new File(file, filename));
			employee.setPicture(logopath+"/"+filename);
		}
		employeeService.save(employee);
		
		ActionContext.getContext().put("message", "添加用户成功");
		ActionContext.getContext().put("urladdress", "employee_list.html");
		return "message";
	}
	
	
	/**
	 * 添加用户界面
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="insert")
	public String addUI()throws Exception{
		
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("id","asc");
		
		this.setDepartments(departmentService.getScrollData(Department.class
				,"o.visible=?1",new Object[]{true},orderby).getResultList());
		this.setPrivilegegroups(privilegeGroupService.getScrollData(PrivilegeGroup.class
				,orderby).getResultList());
		return "add";
	}
	
	
	/**
	 * 修改用户
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="update")
	public String edit()throws Exception{
		
		Employee employee=employeeService.find(Employee.class, this.getUsername());
		employee.setRealname(this.getEmployee().getRealname());
		employee.setSex(Sex.valueOf(this.getSex()));
		employee.setUsercate(UseRole.valueOf(this.getUsercate()));
		IDCard idcard=employee.getIdcard();
		idcard.setBirthday(this.getEmployee().getIdcard().getBirthday());
		idcard.setAddress(this.getEmployee().getIdcard().getAddress());
		employee.setIdcard(idcard);
		employee.setPhone(this.getEmployee().getPhone());
		employee.setEmail(this.getEmployee().getEmail());
		employee.setDegree(this.getEmployee().getDegree());
		if(this.getDepartmentids()!=null && this.getDepartmentids().length>0){
			employee.getDepartments().clear();
			for(Integer id : this.getDepartmentids()){
				employee.addDepartment(new Department(id));
			}
		}
		if(this.getPrivilegegroupids()!=null && this.getPrivilegegroupids().length>0){
			employee.getPrivilegegroups().clear();
			for(Integer id : this.getPrivilegegroupids()){
				employee.addPrivilegegroup(new PrivilegeGroup(id));
			}
		}
		if(this.getImagefile()!=null&&this.getImagefile().length()>0){
			if(!ValidateFile.validateImageFileType(this.getImagefile(),this.getImagefileContentType()
					,this.getImagefileFileName())){
				ActionContext.getContext().put("message", "文件格式不正确,只允许上传gif/jpg/png/bmp图片！");
				ActionContext.getContext().put("urladdress", "javascript:history.back()");
				return "message";
			}
			if(this.getImagefile().length()>204800){
				ActionContext.getContext().put("message", "图片不能大于200K！");
				ActionContext.getContext().put("urladdress", "javascript:history.back()");
				return "message";
			}
			String logopath="/images/employee/"+this.getUsername();
			
			String realpath = ServletActionContext.getServletContext().getRealPath(logopath);
			File file = new File(realpath);
			if(!file.exists()) file.mkdirs();
			String filename=UUID.randomUUID().toString()+"."+ValidateFile.getExtension(this.getImagefileFileName());
			FileUtils.copyFile(this.getImagefile(), new File(file, filename));
			//删除原来的文件
			if(employee.getPicture()!=null){
				realpath=ServletActionContext.getServletContext().getRealPath(employee.getPicture());
				file=new File(realpath);
				if(file.exists())file.delete();
			}
			employee.setPicture(logopath+"/"+filename);
		}
		employeeService.update(employee);
		ActionContext.getContext().put("message", "修改用户资料成功");
		ActionContext.getContext().put("urladdress", "employee_list.html");
		return "message";
	}
	
	
	/**
	 * 修改用户界面
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="update")
	public String editUI()throws Exception{
		
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("id","asc");
		
		this.setDepartments(departmentService.getScrollData(Department.class
				,"o.visible=?1",new Object[]{true},orderby).getResultList());
		this.setPrivilegegroups(privilegeGroupService.getScrollData(PrivilegeGroup.class
				,orderby).getResultList());
		Employee employee=employeeService.find(Employee.class, this.getUsername());
		this.setEmployee(employee);
		this.setSex(employee.getSex().toString());
		this.setUsercate(employee.getUsercate().toString());
		return "edit";
	}
	
	
	/**
	 * 修改个人资料
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="update")
	public String selfEdit()throws Exception{
		
		String name="sa";//ActionContext.getContext().getSession().get("loginName").toString();
		Employee employee=employeeService.find(Employee.class,name);
		employee.setRealname(this.getEmployee().getRealname());
		employee.setSex(Sex.valueOf(this.getSex()));
		employee.setUsercate(UseRole.valueOf(this.getUsercate()));
		IDCard idcard=employee.getIdcard();
		idcard.setBirthday(this.getEmployee().getIdcard().getBirthday());
		idcard.setAddress(this.getEmployee().getIdcard().getAddress());
		employee.setIdcard(idcard);
		employee.setPhone(this.getEmployee().getPhone());
		employee.setEmail(this.getEmployee().getEmail());
		employee.setDegree(this.getEmployee().getDegree());

		if(this.getImagefile()!=null&&this.getImagefile().length()>0){
			if(!ValidateFile.validateImageFileType(this.getImagefile(),this.getImagefileContentType()
					,this.getImagefileFileName())){
				ActionContext.getContext().put("message", "文件格式不正确,只允许上传gif/jpg/png/bmp图片！");
				ActionContext.getContext().put("urladdress", "javascript:history.back()");
				return "message";
			}
			if(this.getImagefile().length()>204800){
				ActionContext.getContext().put("message", "图片不能大于200K！");
				ActionContext.getContext().put("urladdress", "javascript:history.back()");
				return "message";
			}
			String logopath="/images/employee/"+name;
			
			String realpath = ServletActionContext.getServletContext().getRealPath(logopath);
			File file = new File(realpath);
			if(!file.exists()) file.mkdirs();
			String filename=UUID.randomUUID().toString()+"."+ValidateFile.getExtension(this.getImagefileFileName());
			FileUtils.copyFile(this.getImagefile(), new File(file, filename));
			//删除原来的文件
			if(employee.getPicture()!=null){
				realpath=ServletActionContext.getServletContext().getRealPath(employee.getPicture());
				file=new File(realpath);
				if(file.exists())file.delete();
			}
			employee.setPicture(logopath+"/"+filename);
		}
		employeeService.update(employee);
		ActionContext.getContext().put("message", "修改个人资料成功");
		ActionContext.getContext().put("urladdress", "employee_selfEditUI.html");
		return "message";
	}
	
	
	/**
	 * 修改个人资料界面
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="update")
	public String selfEditUI()throws Exception{
		
		String name="sa";//ActionContext.getContext().getSession().get("loginName").toString();
		Employee employee=employeeService.find(Employee.class, name);
		this.setEmployee(employee);
		this.setSex(employee.getSex().toString());
		this.setUsercate(employee.getUsercate().toString());
		return "selfEdit";
	}
	
	
	/**
	 * 修改密码界面
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="update")
	public String editPassUI()throws Exception{
		
		ActionContext.getContext().getSession().put("loginName","sa");
		String name=ActionContext.getContext().getSession().get("loginName").toString();
		this.setUsername(name);
		return "editPass";
	}
	
	
	/**
	 * 修改密码
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="update")
	public String editPass()throws Exception{
		
		String name=ActionContext.getContext().getSession().get("loginName").toString();
		if(employeeService.updatePassword(name, MD5.MD5Encode(this.getEmployee().getPassword()),
				MD5.MD5Encode(this.getEmployee().getRealname()))){
			ActionContext.getContext().put("message", "修改密码成功");
		}
		else{
			ActionContext.getContext().put("message", "修改密码失败");
		}
		ActionContext.getContext().put("urladdress", "employee_editPassUI.html");
		return "message";
	}
	
	
	/**
	 * 查看用户界面
	 * @return
	 */
	@Privilege(model="employee",privilegeValue="view")
	public String viewUI()throws Exception{
		
		LinkedHashMap<String, String> orderby=new LinkedHashMap<String, String>();
		orderby.put("id","asc");
		
		this.setDepartments(departmentService.getScrollData(Department.class
				,"o.visible=?1",new Object[]{true},orderby).getResultList());
		this.setPrivilegegroups(privilegeGroupService.getScrollData(PrivilegeGroup.class
				,orderby).getResultList());
		Employee employee=employeeService.find(Employee.class, this.getUsername());
		this.setEmployee(employee);
		this.setSex(employee.getSex().toString());
		this.setUsercate(employee.getUsercate().toString());
		return "view";
	}
	
	
	/**
	 * 启用用户
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="visible")
	public String visible()throws Exception{
		
		employeeService.setVisible(this.getEmployeeids(), true);
		ActionContext.getContext().put("message", "启用成功");
		ActionContext.getContext().put("urladdress", "employee_list.html");
		return "message";
	}
	
	/**
	 * 禁用用户
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="disvisible")
	public String disvisible()throws Exception{
		
		employeeService.setVisible(this.getEmployeeids(), false);
		ActionContext.getContext().put("message", "禁用成功");
		ActionContext.getContext().put("urladdress", "employee_list.html");
		return "message";
	}
	
	
	/**
	 * 删除用户
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="delete")
	public String delete()throws Exception{
		
		deleteImage(new String[]{this.getUsername()});
		employeeService.delete(Employee.class, this.getUsername());
		ActionContext.getContext().put("message", "删除成功");
		ActionContext.getContext().put("urladdress", "employee_list.html");
		return "message";
	}
	
	/**
	 * 删除用户
	 * @return
	 * @throws Exception
	 */
	@Privilege(model="employee",privilegeValue="delete")
	public String deleteAll()throws Exception{
		
		deleteImage(this.getEmployeeids());
		employeeService.delete(Employee.class, this.getEmployeeids());
		ActionContext.getContext().put("message", "删除成功");
		ActionContext.getContext().put("urladdress", "employee_list.html");
		return "message";
	}

	/**
	 * 根据id删除图片文件
	 * @param ids
	 * @throws Exception
	 */
	private void deleteImage(String[] ids)throws Exception{
		if(ids!=null&&ids.length>0){
			for(String id : ids){
				Employee employee=employeeService.find(Employee.class, id);
				//删除文件
				if(employee!=null&&employee.getPicture()!=null){
					String realpath=ServletActionContext.getServletContext().getRealPath(employee.getPicture());
					File file=new File(realpath);
					if(file.exists())file.delete();
				}
			}
		}
	}
	
	
	public int getPage() {
		return page<1?1:page;
	}
	public void setPage(int page) {
		this.page = page;
	}

	public String getQuery() {
		return query;
	}
	public void setQuery(String query) {
		this.query = query;
	}

	public PageView<Employee> getPageView() {
		return pageView;
	}
	public void setPageView(PageView<Employee> pageView) {
		this.pageView = pageView;
	}

	public Employee getEmployee() {
		return employee;
	}
	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getUsercate() {
		return usercate;
	}
	public void setUsercate(String usercate) {
		this.usercate = usercate;
	}

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}

	public String getCardno() {
		return cardno;
	}
	public void setCardno(String cardno) {
		this.cardno = cardno;
	}

	public List<Department> getDepartments() {
		return departments;
	}
	public void setDepartments(List<Department> departments) {
		this.departments = departments;
	}

	public List<PrivilegeGroup> getPrivilegegroups() {
		return privilegegroups;
	}
	public void setPrivilegegroups(List<PrivilegeGroup> privilegegroups) {
		this.privilegegroups = privilegegroups;
	}

	public Integer[] getDepartmentids() {
		return departmentids;
	}
	public void setDepartmentids(Integer[] departmentids) {
		this.departmentids = departmentids;
	}

	public Integer[] getPrivilegegroupids() {
		return privilegegroupids;
	}
	public void setPrivilegegroupids(Integer[] privilegegroupids) {
		this.privilegegroupids = privilegegroupids;
	}

	public String[] getEmployeeids() {
		return employeeids;
	}
	public void setEmployeeids(String[] employeeids) {
		this.employeeids = employeeids;
	}

	public File getImagefile() {
		return imagefile;
	}
	public void setImagefile(File imagefile) {
		this.imagefile = imagefile;
	}

	public String getImagefileContentType() {
		return imagefileContentType;
	}
	public void setImagefileContentType(String imagefileContentType) {
		this.imagefileContentType = imagefileContentType;
	}

	public String getImagefileFileName() {
		return imagefileFileName;
	}
	public void setImagefileFileName(String imagefileFileName) {
		this.imagefileFileName = imagefileFileName;
	}
}
